#include "gui_textbox.h"

textbox* gui_textbox_new_empty(main_obj *mobj) {
    Uint32 rmask, gmask, bmask, amask;
    /* SDL interprets each pixel as a 32-bit number, so our masks must depend
       on the endianness (byte order) of the machine */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    rmask = 0xff000000;
    gmask = 0x00ff0000;
    bmask = 0x0000ff00;
    amask = 0x000000ff;
#else
    rmask = 0x000000ff;
    gmask = 0x0000ff00;
    bmask = 0x00ff0000;
    amask = 0xff000000;
#endif
    textbox *t;
    t = g_malloc0(sizeof (textbox));
    t->posx = 0;
    t->posy = 0;
    t->mode = GUI_TEXTBOX_MODE_NORMAL;
    t->text = g_string_new("");
    t->ptext = g_string_new("");
    t->update = gui_textbox_update;
    t->paint = gui_textbox_normal_paint;
    t->click = gui_textbox_click;
    t->ge.redraw = TRUE;
    t->ge.posx = 0;
    t->ge.posy = 0;
    t->ge.type = GUI_TEXTBOX;
    t->ge.graphic = SDL_CreateRGBSurface(SDL_HWSURFACE, 150, 30, 32, rmask, gmask, bmask, amask);
    //SDL_FillRect(t->ge.graphic, NULL, SDL_MapRGBA(t->ge.graphic->format, 0, 0, 0, 0));
    //SDL_SetAlpha()
    return t;
}

gboolean gui_textbox_click(main_obj *mobj, textbox *t) {
    mobj->gm->focused_element = (gpointer) t;
    return TRUE;
}

gboolean gui_textbox_update(main_obj *mobj, textbox *t) {
    if (t->ge.focused) {
        if (mobj->event->type == SDL_KEYDOWN) {
            t->text = g_string_append(t->text, gui_util_convert_key_to_char(mobj, mobj->event->key.keysym.sym));
            t->ptext = g_string_append(t->ptext, "*");
            t->ge.redraw = TRUE;
        }
    }
    return TRUE;
}

gboolean gui_textbox_normal_paint(main_obj *mobj, textbox *t) {
    //g_debug("drawing textbox");
    //textbox *t = (textbox*) mobj->gm->element_to_draw;
    //SDL_FillRect(t->ge.graphic, NULL, SDL_MapRGB(mobj->main_screen->format, 0, 0, 0));
    SDL_FillRect(t->ge.graphic, NULL, SDL_MapRGBA(t->ge.graphic->format, 0, 0, 0, 0));
    roundedBoxRGBA(t->ge.graphic, 0, 0, t->ge.graphic->w, t->ge.graphic->h, 5, 250, 250, 250, 200);
    SDL_Surface *text;
    switch(t->mode)
    {
        case (GUI_TEXTBOX_MODE_NORMAL):
        {
            text = gui_util_drawtext(mobj->gm->current_font, 255, 255, 255, 255, 0, 0, 0, 1, t->text->str);
            break;
        }
        case (GUI_TEXTBOX_MODE_PASSWORD):
        {
            text = gui_util_drawtext(mobj->gm->current_font, 255, 255, 255, 255, 0, 0, 0, 1, t->ptext->str);
            break;
        }
    }
    
    if (text != NULL) {
        //g_debug("fond rendered");
        SDL_Rect rect;
        rect.x = 0;
        rect.y = (t->ge.graphic->h / 2) - (text->h / 2);
        SDL_BlitSurface(text, 0, t->ge.graphic, &rect);
        //g_debug("painted");
        return TRUE;
    }
    return TRUE;
}

void gui_textbox_set_mode(textbox *t, int mode)
{
    t->mode = mode;
}
